<?php

namespace app\commission;

use app\models\merchant\MerchantOrder;
use app\models\merchant\MerchantPayFor;
use app\models\pay\PayFor;
use app\models\user\UserAccount;
use app\models\user\UserCash;
use app\models\user\UserConsume;
use app\util\Debug;

/**
 * Class PayForFinish
 * @package app\commission
 */
class PayForFinish
{
    public static function forFinish(PayFor $for)
    {
        try {

            if ($for->type == 1) {

                // user cash
                self::cash($for);

            } else if ($for->type == 2) {

                // merchant pay
                self::merchant($for);
            }

        } catch (\Exception $e) {
            Debug::debug('pay-for-finish-error', $e->getMessage());
        }
    }

    protected static function cash(PayFor $for)
    {
        /*
         * 1) user_cash status
         * 2) user account unlock
         * 3) consume
         */

        $cash = UserCash::findOne(['sn' => $for->sn]);
        $cash->status = 1;
        $cash->save();

        // account unlock
        // $account = UserAccount::findOne(['user_id' => $cash->user_id]);
        // if ($account->lock_balance >= $cash->amount) {
        //     $account->lock_balance -= $cash->amount;
        //     $account->save();
        // }

        $consume = new UserConsume();
        $consume->user_id = $cash->user_id;
        $consume->balance = $cash->amount;
        $consume->cash_id = $cash->id;
        $consume->status = 1;
        $consume->text = '提现';
        $consume->save();
    }

    protected static function merchant(PayFor $for)
    {
        /*
         * 1) merchant_pay_for & merchant_order status
         * 2) commission
         */

        $merchantPayFor = MerchantPayFor::findOne(['sn' => $for->sn]);
        $merchantPayFor->status = 1;
        $merchantPayFor->save();

        $merchantOrder = MerchantOrder::findOne(['sn' => $merchantPayFor->pay_sn]);
        $merchantOrder->status = 2;
        $merchantOrder->save();

        // commission
        Commission::getInstance()->getMerchant()->commission($merchantOrder);
    }
}